﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Data;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using Meraz.Core.Parsers;
using Meraz.Core.Managers;
using System.Diagnostics;
using Meraz.Core.Helpers;
using Ninject;

namespace Meraz.Core.Commands
{
    public class CreateDomainsSqlCommand : BaseCommand, ICreateDomainsCommand 
    {
        [Inject]
        public CreateDomainsSqlCommand(INetworkHelper networkHelper)
        {
            this.NetworkHelper = networkHelper ?? new NetworkHelper();
        }
        public INetworkHelper NetworkHelper { get; set; }

        public Domain Execute(string url)
        {
            IDictionary<string, Domain> dict = Execute(new string[] { url });
            return dict[url];
        }
        public IDictionary<string, Domain> Execute(IEnumerable<string> urls)
        {
            Dictionary<string, Domain> dict = new Dictionary<string, Domain>();
            Dictionary<string, Domain> allDomains = new Dictionary<string,Domain>();
            foreach (string url in urls)
            {
                IEnumerable<string> domainNames = NetworkHelper.ExtractDomains(url).Reverse();
                List<Domain> urlDomains = new List<Domain>();
                int parentID = 0;
                for (int domainIndex = 0; domainIndex < domainNames.Count(); domainIndex++)
                {
                    string domainName = domainNames.ElementAt(domainIndex);
                    Domain result = null;

                    int domainID = MerazContext.Instance.CreateDomain(domainName, parentID);
                    result = new Domain() { ID = domainID, Name = domainName, ParentID = parentID };

                    parentID = result.ID;
                    allDomains[domainName] = result;
                    urlDomains.Add(result);
                }
                dict[url] = urlDomains.LastOrDefault();
            }
            return dict;
        }
    }
}
